using System;
using System.Text.RegularExpressions;

namespace TLDRML.Tokens
{
    public class StringToken : Token
    {
        public string Value { get; set; }

        public StringToken(TokenPosition position, string value)
            : base(position)
        {
            Value = value;
        }

        public override string ToString()
        {
            return String.Format("[STRING: {0}]", Value);
        }

        public bool Equals(StringToken other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return base.Equals(other) && Equals(other.Value, Value);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            return Equals(obj as StringToken);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (base.GetHashCode()*397) ^ (Value != null ? Value.GetHashCode() : 0);
            }
        }
    }

    public class StringTokenDefinition : TokenDefinition
    {
        // Confession time! I didn't write this.. I stole it from: http://wordaligned.org/articles/string-literals-and-regular-expressions
        public StringTokenDefinition()
            : base(new Regex("\"([^\"\\\\]|\\\\.)*\"", RegexOptions.Compiled))
        {
        }

        public override Token Create(TokenPosition tokenPosition, string value)
        {
            return new StringToken(tokenPosition, value.Trim('"')
                .Replace("\\\"", "\"")
                .Replace("\\\\", "\\"));
        }
    }
}